import type { Ref } from 'vue';

import { shallowRef } from 'vue';

import { echarts } from '#/utils';

export type EChartsCoreOption = echarts.EChartsCoreOption;

//  Echarts对象不建议直接定义成响应式，一会使得复杂对象被代理后出现异常，而是为了深度监听复杂对象引起图表渲染性能问题，因此用shallowRef包裹
const useEcharts = (elRef: Ref<HTMLDivElement>, options: EChartsCoreOption) => {
  const charts = shallowRef<echarts.ECharts>();

  const setOptions = (options: EChartsCoreOption) => {
    // notMerge 参数设置为 true
    charts.value?.setOption(options, true);
  };
  const initCharts = () => {
    charts.value = echarts.init(elRef.value);
    setOptions(options);
  };

  const echartsResize = () => {
    charts.value?.resize();
  };

  const destroyCharts = () => {
    charts.value?.dispose();
  };
  //  监听窗口，需要时启用
  // onMounted(() => {
  //   window.addEventListener("resize", echartsResize)
  // })
  // // 防止 echarts 页面 keepAlive 时，还在继续监听页面
  // onDeactivated(() => {
  //   window.removeEventListener("resize", echartsResize)
  // })

  // onBeforeUnmount(() => {
  //   window.removeEventListener("resize", echartsResize)
  // })
  return {
    initCharts,
    setOptions,
    echartsResize,
    destroyCharts,
  };
};
export { useEcharts };
